package com.wrial.kind.linkedList;
/*
 * @Author  Wrial
 * @Date Created in 13:57 2020/8/9
 * @Description  在 O(n log n) 时间复杂度和常数级空间复杂度下，对链表进行排序。
 */

public class SortList {

    /**
     * 因为要求O(nlogn)时间复杂度，所有需要使用分散性排序，因此使用归并排序
     */
    public ListNode sortList(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode ans = new ListNode(-1);
        ListNode fast = head.next, slow = head;
        // 找出中点
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }

        ListNode temp = slow.next;
        slow.next = null;
        ListNode left = sortList(head);
        ListNode right = sortList(temp);
        ListNode p = ans;
        while (left!=null&&right!=null){
            if (left.val<right.val){
                p.next = left;
                left = left.next;
            }else {
                p.next = right;
                right = right.next;
            }
            p = p.next;
        }
        p.next = left == null ? right : left;
        return ans.next;

    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
